package collection.map;

import org.junit.Test;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * HashMap和TreeMap
 * 如果要得到一个有序的结果，可以使用TreeMap，TreeMap的底层是红黑树，时间复杂度是O(logN)，而HashMap的底层是哈希表，时间复杂度是O(1)
 * TreeMap的key必须实现Comparable接口，否则会抛出java.lang.ClassCastException异常
 * 在使用TreeMap的时候，获取倒序的结果，可以使用TreeMap的descendingMap()方法
 */
public class HashAndTreeMap {

    @Test
    public void test1() {
        Map<BigDecimal, String> hashMap = new TreeMap<>();
        hashMap.put(new BigDecimal("0.1"), "A");
        hashMap.put(new BigDecimal("10.3"), "C");
        hashMap.put(new BigDecimal("60.3"), "D");
        hashMap.put(new BigDecimal("0.2"), "B");
        for (Map.Entry<BigDecimal, String> entry : hashMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }

    public static void main(String[] args) {
        Map<Key1, String> hashMap1 = new HashMap<>();
        hashMap1.put(new Key1(1), "A");
        hashMap1.put(new Key1(2), "B");
        hashMap1.put(new Key1(3), "C");
        hashMap1.put(new Key1(4), "D");

        // 遍历map
        for (Map.Entry<Key1, String> entry : hashMap1.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
        System.out.println("----------------");


        Map<Key1, String> treeMap1 = new TreeMap<>();
        treeMap1.put(new Key1(1), "A");
        treeMap1.put(new Key1(2), "B");
        treeMap1.put(new Key1(3), "C");
        treeMap1.put(new Key1(4), "D");

        // 遍历map
        for (Map.Entry<Key1, String> entry : treeMap1.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
        System.out.println("----------------");

        Map<Key2, String> treeMap2 = new TreeMap<>();
        treeMap2.put(new Key2(1), "A");
        treeMap2.put(new Key2(2), "B");
        treeMap2.put(new Key2(6), "C");
        treeMap2.put(new Key2(4), "D");

        // 遍历map
        for (Map.Entry<Key2, String> entry : treeMap2.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
        System.out.println("----------------");

    }

    static class Key1 implements Comparable<Key1> {
        private Integer key;

        public Key1(Integer key) {
            this.key = key;
        }

        @Override
        public int compareTo(Key1 o) {
            return this.key.compareTo(o.key);
        }
    }

    static class Key2 {
        private Integer key;

        public Key2(Integer key) {
            this.key = key;
        }
    }
}
